package com.ruoyi.biz.homepage.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.biz.category.service.IBizCategoryService;
import com.ruoyi.biz.homepage.domain.HomePageLetterVo;
import com.ruoyi.biz.homepage.domain.HomePageVo;
import com.ruoyi.biz.homepage.mapper.DispatchMapper;
import com.ruoyi.biz.homepage.mapper.HomePageMapper;
import com.ruoyi.biz.homepage.service.IHomePageService;
import com.ruoyi.biz.letter.domain.BizCityLetter;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.BizCategory;
import com.ruoyi.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Fei.Cong
 * @date 2024-09-03 9:14
 */
@Slf4j
@Service
public class UnResolvedReportServiceImpl implements IHomePageService {

    @Autowired
    private DispatchMapper dispatchMapper;

    @Autowired
    private HomePageMapper homePageMapper;

    @Autowired
    private IBizCategoryService bizCategoryService;

    @Override
    public List<HomePageVo> totallist(BizCityLetter bizCityLetter) {
        bizCityLetter.setBillMonths(DateUtils.getMonthRange(bizCityLetter.getBeginDate(), bizCityLetter.getEndDate()));
        //查询地市与部门列表
        List<HomePageVo> list = homePageMapper.selectDeptlist(bizCityLetter);
        // 查询地市下属部门数量
        List<HomePageVo> deptlist = homePageMapper.selectDeptNum();
        //查询地市与部门认领信息分类统计
        List<HomePageLetterVo> letterlist = homePageMapper.selectLetterlist(bizCityLetter);

        List<HomePageLetterVo> letterSolvelist = dispatchMapper.selectLetterSolvelist(bizCityLetter);

        List<HomePageLetterVo> solveList = dispatchMapper.selectReasonableAndSolve(bizCityLetter);
        List<HomePageLetterVo> expireCaseList = dispatchMapper.selectExpireCase(bizCityLetter);
        List<HomePageLetterVo> expireFinishedCaseList = dispatchMapper.selectCaseFinished(bizCityLetter);

        Map<Long, Long> solveMap = solveList.stream().collect(Collectors.toMap(k -> k.getDeptId(), v -> v.getOnlyTypeNum()));
        Map<Long, Long> expireCaseMap = expireCaseList.stream().collect(Collectors.toMap(k -> k.getDeptId(), v -> v.getOnlyTypeNum()));
        Map<Long, Long> expireFinishedCaseMap = expireFinishedCaseList.stream().collect(Collectors.toMap(k -> k.getDeptId(), v -> v.getOnlyTypeNum()));

        List<TreeSelect> catlist = getCategoryList();
        List<HomePageLetterVo> templist = new ArrayList<HomePageLetterVo>();
        for (HomePageVo vo : list) {
            //交办数量=确认数量+退回数量；
            Long jiaobanNum = vo.getJiaobanNum();
            Long querenNum = 0L;  // 确认数量
            Long youliNum = 0L;  // 有理访
            Long wuliNum = 0L; // 无理访

            for (HomePageLetterVo sub : letterlist) {
                // 关联同一部门下数据
                if (vo.getDeptId().equals(sub.getDeptId())) {
                    //  是否有理，1有理，2无理，3部分有理
                    if ("1".equals(sub.getIsReasonable())) {
                        youliNum = youliNum + sub.getOnlyTypeNum();
                    } else {
                        wuliNum = wuliNum + sub.getOnlyTypeNum();
                    }
                }
            }

            //确认数量=有理访数+无理访数；
            querenNum = youliNum + wuliNum;
            vo.setQuerenNum(querenNum);
            vo.setYouliNum(youliNum);
            vo.setYouliTypeNum(youliNum);
            vo.setWuliNum(wuliNum);
            vo.setWuliTypeNum(wuliNum);
            vo.setJiaobanNum(vo.getTuihuiNum()+querenNum);
            if (solveMap.containsKey(vo.getDeptId())) {
                vo.setYlhjNum(solveMap.get(vo.getDeptId()));
            }
            if (expireCaseMap.containsKey(vo.getDeptId())) {
                vo.setDqajNum(expireCaseMap.get(vo.getDeptId()));
            }
            if (expireFinishedCaseMap.containsKey(vo.getDeptId())) {
                vo.setDqajbjNum(expireFinishedCaseMap.get(vo.getDeptId()));
            }
            if (Objects.nonNull(vo.getYlhjNum()) && vo.getYouliNum() != 0) {
                BigDecimal ylhj = NumberUtil.round(NumberUtil.mul(NumberUtil.div(vo.getYlhjNum(), vo.getYouliNum()), 100), 2);
                vo.setHjPercent(ylhj + "%");
            }
            if (Objects.nonNull(vo.getDqajbjNum()) && vo.getDqajNum() != 0) {
                BigDecimal dqajbj = NumberUtil.round(NumberUtil.mul(NumberUtil.div(vo.getDqajbjNum(), vo.getDqajNum()), 100), 2);
                vo.setDqbjPercent(dqajbj.toString().concat("%"));
            }
            List<Long> otherlist = new ArrayList<Long>();
            otherlist.add(vo.getYlhjNum()); //有理访化解分类数
            for (TreeSelect m : catlist) {
                // 有二级分类
                if (m.getChildren().size() > 0) {
                    for (TreeSelect kk : m.getChildren()) {
                        Long onlyTypeNum = getSolveOnlyTypeNum(Long.parseLong(m.getValue()), Long.parseLong(kk.getValue()), letterSolvelist, vo.getDeptId());
                        otherlist.add(onlyTypeNum);
                    }
                } else {
                    Long onlyTypeNum = getSolveOnlyTypeNum(Long.parseLong(m.getValue()), 0L, letterSolvelist, vo.getDeptId());
                    otherlist.add(onlyTypeNum);
                }
            }
            vo.setCategoryList(otherlist);
        }
        for (HomePageVo vo : list) {
            A:
            for (HomePageVo deptrow : deptlist) {
                if (vo.getCityCode().equals(deptrow.getCityCode())) {
                    vo.setMergeRows(deptrow.getJiaobanNum());
                    deptrow.setCityCode(1L);
                    break A;
                }
            }
//            Long tuihui_tmp = 0L;
//            for (HomePageVo vo2 : list) {
//                // 确认是同一地市
//                if (vo.getCityCode().equals(vo2.getCityCode())) {
//                    tuihui_tmp = tuihui_tmp + vo2.getQuerenNum();
//                }
//            }
//            //退回数量   交办数量=确认数量+退回数量；
//            vo.setTuihuiNum(vo.getJiaobanNum() - tuihui_tmp);
        }
        buildTotalCategory(list);

        return list;
    }

    /**
     * 根据一级，二级，获取结果
     */
    public Long getOnlyTypeNum(Long pCategoryId, Long sCategoryId, List<HomePageLetterVo> letterlist, String isReasonable, Long deptId) {
        Long onlyTypeNum = 0L;
        for (HomePageLetterVo sub : letterlist) {
            // 关联同一部门下数据
            if (sub.getDeptId().equals(deptId)
                    && isReasonable.equals(sub.getIsReasonable())
                    && (Objects.nonNull(sub.getpCategoryId()) &&sub.getpCategoryId().equals(pCategoryId))
                    && (Objects.nonNull(sub.getsCategoryId()) && sub.getsCategoryId().equals(sCategoryId))) {
                onlyTypeNum = sub.getOnlyTypeNum();
            }
        }
        return onlyTypeNum;
    }

    public Long getSolveOnlyTypeNum(Long pCategoryId, Long sCategoryId, List<HomePageLetterVo> letterlist, Long deptId) {
        Long onlyTypeNum = 0L;
        for (HomePageLetterVo sub : letterlist) {
            // 关联同一部门下数据
            if (sub.getDeptId().equals(deptId)
                    && (Objects.nonNull(sub.getpCategoryId()) &&sub.getpCategoryId().equals(pCategoryId))
                    && (Objects.nonNull(sub.getsCategoryId()) && sub.getsCategoryId().equals(sCategoryId))) {
                onlyTypeNum = sub.getOnlyTypeNum();
            }
        }
        return onlyTypeNum;
    }

    public List<TreeSelect> getCategoryList() {
        LambdaQueryWrapper<BizCategory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(BizCategory::getOrderNum);
        List<BizCategory> menus = bizCategoryService.list(lambdaQueryWrapper);
        return bizCategoryService.buildMenuTreeSelect(menus);
    }

}
